<template>
  <el-dialog
    v-model="dialogVisible"
    :title="currentStep === 1 ? '忘记密码 - 身份验证' : '忘记密码 - 重置密码'"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="!loading"
    @closed="handleDialogClosed"
  >
    <!-- 步骤指示器 -->
    <el-steps :active="currentStep" finish-status="success" simple>
      <el-step title="身份验证" />
      <el-step title="重置密码" />
    </el-steps>
    
    <!-- 步骤1: 身份验证 -->
    <el-form
      v-if="currentStep === 1"
      ref="verifyFormRef"
      :model="verifyForm"
      :rules="verifyRules"
      label-width="100px"
      class="verify-form"
      v-loading="loading"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="verifyForm.username" placeholder="请输入用户名" />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="verifyForm.email" placeholder="请输入邮箱" />
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="verifyForm.phone" placeholder="请输入手机号" />
      </el-form-item>
    </el-form>
    
    <!-- 步骤2: 重置密码 -->
    <el-form
      v-else
      ref="resetFormRef"
      :model="resetForm"
      :rules="resetRules"
      label-width="100px"
      class="reset-form"
      v-loading="loading"
    >
      <el-form-item label="新密码" prop="newPassword">
        <el-input 
          v-model="resetForm.newPassword" 
          type="password" 
          show-password
          placeholder="请输入新密码" 
        />
      </el-form-item>
      
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input 
          v-model="resetForm.confirmPassword" 
          type="password" 
          show-password
          placeholder="请再次输入新密码" 
        />
      </el-form-item>
      
      <div class="password-tips">
        <p>密码要求：</p>
        <ul>
          <li>长度至少8个字符</li>
          <li>包含字母和数字</li>
        </ul>
      </div>
    </el-form>
    
    <!-- 对话框底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false" :disabled="loading">取消</el-button>
        <el-button v-if="currentStep === 1" type="primary" @click="verifyIdentity" :loading="loading">
          验证身份
        </el-button>
        <el-button v-else type="primary" @click="resetPassword" :loading="loading">
          重置密码
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineExpose, defineEmits } from 'vue';
import { ElMessage } from 'element-plus';
import { verifyIdentity as verifyUserIdentity, resetPassword as resetUserPassword } from '@/api/user';

const emit = defineEmits(['success']);

// 对话框可见性
const dialogVisible = ref(false);

// 当前步骤 (1: 身份验证, 2: 重置密码)
const currentStep = ref(1);

// 加载状态
const loading = ref(false);

// 验证令牌
const verificationToken = ref('');

// 表单引用
const verifyFormRef = ref(null);
const resetFormRef = ref(null);

// 身份验证表单
const verifyForm = reactive({
  username: '',
  email: '',
  phone: ''
});

// 重置密码表单
const resetForm = reactive({
  newPassword: '',
  confirmPassword: '',
  verificationToken: ''
});

// 身份验证表单验证规则
const verifyRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
};

// 重置密码表单验证规则
const resetRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少为8个字符', trigger: 'blur' },
    // { 
    //   pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/, 
    //   message: '密码必须包含字母和数字', 
    //   trigger: 'blur' 
    // }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 验证用户身份
const verifyIdentity = async () => {
  if (!verifyFormRef.value) return;
  
  await verifyFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    loading.value = true;
    
    try {
      const response = await verifyUserIdentity({
        username: verifyForm.username,
        email: verifyForm.email,
        phone: verifyForm.phone
      });
      
      console.log('身份验证响应:', response); // 添加日志，查看响应结构
      
      // 直接检查response中是否包含verificationToken
      if (response && response.code == 200) {
        ElMessage.success('身份验证成功');
        verificationToken.value = response.data.verificationToken;
        resetForm.verificationToken = response.data.verificationToken;
        currentStep.value = 2; // 进入重置密码步骤
      } else {
        ElMessage.error('error：' + response.message);
      }
    } catch (error) {
      ElMessage.error('error: ' + response.message);
    } finally {
      loading.value = false;
    }
  });
};

// 重置密码
const resetPassword = async () => {
  if (!resetFormRef.value) return;
  
  await resetFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    loading.value = true;
    
    try {
      const response = await resetUserPassword({
        verificationToken: resetForm.verificationToken,
        newPassword: resetForm.newPassword,
        confirmPassword: resetForm.confirmPassword
      });
      
      console.log('重置密码响应:', response); // 添加日志，查看响应结构
    
      if (response && response.code == 200) {
        ElMessage.success('密码重置成功');
        emit('success');
        dialogVisible.value = false;
      } else {
        ElMessage.error('error：' + response.message);
      }
    } catch (error) {
      console.error('密码重置请求失败:', error);
      ElMessage.error(error.message || '密码重置失败，请稍后再试');
    } finally {
      loading.value = false;
    }
  });
};

// 处理对话框关闭
const handleDialogClosed = () => {
  // 重置表单和状态
  currentStep.value = 1;
  verificationToken.value = '';
  
  if (verifyFormRef.value) {
    verifyFormRef.value.resetFields();
  }
  
  if (resetFormRef.value) {
    resetFormRef.value.resetFields();
  }
};

// 打开对话框的方法
const open = () => {
  dialogVisible.value = true;
};

// 暴露方法给父组件
defineExpose({
  open
});
</script>

<style scoped>
.el-steps {
  margin-bottom: 20px;
}

.verify-form,
.reset-form {
  margin: 20px 0;
}

.password-tips {
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}

.password-tips p {
  margin: 0 0 5px 0;
}

.password-tips ul {
  margin: 0;
  padding-left: 20px;
}

.password-tips li {
  margin-bottom: 5px;
}
</style> 